from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests,functools
from application.models.users.user import *
from db import db
from tools.Myredis import r
home_blue = Blueprint("homeblue", __name__)


# 获取所有标签
def getTags():
    sql = "select * from tags"
    res = db.findAll(sql)
    return res


# 获取所有类型
def getctype():
    sql = "select * from ctype"
    res = db.findAll(sql)
    return res


# @home_blue.route("/home")
# def gethome():
#     ctypetlist = getctype()
#     tagslist = getTags()
#     return jsonify({
#         "code": 200,
#         "ctypelist": ctypetlist,
#         "tagslist": tagslist
#     })


@home_blue.route("/getHomeCourse")
def getHomeGourse1():
    # 获取类型
    ctypetlist = getctype()
    # 获取标签
    tagslist = getTags()
    # 获取当前页面
    page = request.args.get("page")
    # 获取查询条件
    tagid = request.args.get("tagid")
    typeid = request.args.get("type")
    is_publish = request.args.get("is_publish")
    # 排序条件
    orderbyid = request.args.get("orderbyid")
    # 定义一个空值，方便拼接字段
    where = ""
    if int(typeid) > 0:
        where = where + " and c.ctype=" + typeid
    if int(is_publish) > 0:
        where = where + " and c.is_publish=" + is_publish
    if int(tagid) > 0:
        tsql = "select count(c.id) as tcount from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
        sql = "select * from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid="+tagid
    else:
        sql = "select * from course as c  where 1=1"
        tsql = "select count(c.id) as  tcount   from course as c  where 1=1"

    if where:
        sql = sql + " " + where
        tsql = tsql + " " + where

    if int(orderbyid) > 0:
        if int(orderbyid) == 1:
            sql = sql + " order by c.id desc"
        else:
            sql = sql + " order by c.views desc"

    # 查询总共有多少条
    res = db.findone(tsql)
    total = res['tcount']
    page_size = 2
    start = (int(page)-1)*page_size
    sql = sql + " limit %d,%d" % (start, page_size)
    courselist = db.findAll(sql)
    print(sql)
    return jsonify({"code": 200, "tlist": ctypetlist, 'taglist': tagslist, 'clist': courselist, "total": total, "page_size":  page_size})


@home_blue.route('/detail')
def detail():
    # 获取课程id
    id = request.args.get('id')
    sql = "select c.id,s.id as sid,c.descrip,c.tcount,s.name,s.url,s.type,c.ctype from course as c inner join jie as s on c.id=s.courseid where c.id=%d" % (
        int(id))
    res = db.findAll(sql)
    section = []
    course=[]
    for i in res:
        print(i)
        d = {
            'id': i['sid'], 'name': i['name'], 'url': i['url'], "type": i['type'], 'courseid': i['id']
        }
        section.append(d)
        course = [{'id': i['id'], 'ctype': i['ctype'], 'name':i['name'],
                  'descrip': i['descrip'], 'tcount': i['tcount']}]
    key = "course"+str(id)
    skey = "jie" + str(id)
    r.add_str(key,json.dumps(course))
    r.add_str(skey,json.dumps(section))
    return jsonify({'code': 200, 'clist': course, 'slist': section})

@home_blue.route('/Video')
def Video():
    # 获取用户id和章节id
    courseid = request.args.get("courseid")
    userid = request.args.get("userid")
    id = request.args.get("id")
    # 通过用户表查询用户级别
    sql = "select level from user where id=%d"%(int(userid))
    user = db.findAll(sql)
    print(user)
    # 通过课程id查询课程的类型
    key = "jie"+str(courseid)
    course = r.get_str(key)
    if course:
        course = json.loads(course)
        for i in course:
            print(i)
            ctype=i["type"]
            if int(ctype) == 2:
                # 会员可看
                for j in user:
                    user = j["level"]
                    if int(user) != 2:
                        return jsonify({"code": 10011, "msg":"此用户没有权限观看"})
                    # 课程type=3  需要购买课程
                    if int(ctype) == 3:
                        bsql = "select * from vipuser_course where userid=%d and courseid=%d"%(int(userid),int(courseid))
                        bres = db.findone(bsql)
                        if not bres:
                            return jsonify({"code": 10012, "msg":"此课程需要单独购买"})
                    # 获取此课程下的所有章节
                    skey = "jie"+str(courseid)
                    jie = json.loads(r.get_str(skey))
                    for i in jie:
                        if int(i["id"]) == int(id):
                            url = i["url"]
                    # 返回此章节播放的url
                    return jsonify({"code": 200, "msg":"获取成功", "url": url})
            else:
                return jsonify({"code": 10011, "msg": "请开通会员"})
    else:
        return jsonify({"code": 10010})






